package org.tis.tools.abf.module.om.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.abf.module.ac.entity.AcApp;
import org.tis.tools.abf.module.ac.entity.AcOperator;
import org.tis.tools.abf.module.ac.entity.AcRole;
import org.tis.tools.abf.module.ac.service.IAcAppService;
import org.tis.tools.abf.module.ac.service.IAcOperatorService;
import org.tis.tools.abf.module.common.entity.Tree;
import org.tis.tools.abf.module.common.entity.enums.YON;
import org.tis.tools.abf.module.common.entity.vo.TreeDetail;
import org.tis.tools.abf.module.om.controller.request.OmPositionRequest;
import org.tis.tools.abf.module.om.dao.OmGroupMapper;
import org.tis.tools.abf.module.om.entity.*;
import org.tis.tools.abf.module.om.entity.enums.OmGroupStatus;
import org.tis.tools.abf.module.om.entity.enums.OmGroupType;
import org.tis.tools.abf.module.om.entity.enums.OmPositionType;
import org.tis.tools.abf.module.om.entity.vo.OmEmployeeOperatorDetail;
import org.tis.tools.abf.module.om.entity.vo.OmGroupPositionDetail;
import org.tis.tools.abf.module.om.entity.vo.OmPositionDetail;
import org.tis.tools.abf.module.om.exception.OMExceptionCodes;
import org.tis.tools.abf.module.om.exception.OrgManagementException;
import org.tis.tools.abf.module.om.service.*;
import org.tis.tools.abf.module.sys.service.ISysSeqnoService;
import org.tis.tools.core.utils.StringUtil;
import org.tis.tools.model.exception.i18.ExceptionCodes;

import java.math.BigDecimal;
import java.util.*;

import static org.tis.tools.core.utils.BasicUtil.wrap;

/**
 * omGroup的Service接口实现类
 * 
 * @author ljhua
 * @date 2018/04/23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OmGroupServiceImpl extends ServiceImpl<OmGroupMapper, OmGroup> implements IOmGroupService {

    @Autowired
    IOmOrgService omOrgService;
    @Autowired
    IOmEmpGroupService omEmpGroupService;
    @Autowired
    IOmEmployeeService omEmployeeService;
    @Autowired
    IOmPositionService omPositionService;
    @Autowired
    IOmGroupAppService omGroupAppService;
    @Autowired
    ISysSeqnoService seqnoRService;
    @Autowired
    IAcAppService acAppService;
    @Autowired
    IAcOperatorService operatorService;
    @Autowired
    IOmEmpPositionService omEmpPositionService;

    /**
     * 重新排序： 自增
     */
    private static final String REORDER_AUTO_PLUS = "plus";
    /**
     * 重新排序： 自减
     */
    private static final String REORDER_AUTO_MINUS = "minus";

    @Override
    public String genGroupCode(String groupType) throws OrgManagementException {
        if(groupType == null) {
            throw new OrgManagementException(OMExceptionCodes.LAKE_PARMS_FOR_GEN_GROUPCODE,new Object[]{"groupType"}) ;
        }
        /**
         * <pre>
         * 工作组代码规则：
         * 1.共10位+GROUP前缀；
         * 2.组成结构： 工作组类别(两位) + 序号(八位)
         * 序号：全行范围内职务数量顺序排号
         * </pre>
         */
        StringBuffer sb = new StringBuffer() ;
        //翻译类型-NORMAL=01 PROJECT=02 AFFAIR=03
        String type = "";
        if(groupType.equals("normal")){
            type = "01";
        }else if(groupType.equals("project")){
            type = "02";
        }else if(groupType.equals("affair")){
            type = "03";
        }else{
            throw new OrgManagementException(OMExceptionCodes.LAKE_PARMS_FOR_GEN_GROUPCODE,new Object[]{"groupType"}) ;
        }
        // 开始生成
        sb.append(type) ;
//		sb.append(toSeqNO(sequenceService.getNextSeqNo(BOSHGenGroupCode.class.getName()))) ;//五位机构顺序号
        sb.append(toSeqNO(seqnoRService.getNextSequence("GROUP_CODE", "工作组代码序号")));
        return "GROUP"+sb.toString();
    }

    @Override
    public OmGroup selectGroupByCode(String groupCode){

        OmGroup og = queryGroupByCode(groupCode);
        return og;
    }

    @Override
    public void createGroup(OmGroupType groupType, String groupName, String guidOrg, String parentGroupCode, String groupDesc) throws OrgManagementException {
        //创建修改工作组序列对象
        OmGroup omGroup = new OmGroup();

        EntityWrapper<OmOrg> omOrgEntityWrapper = new EntityWrapper<>();
        omOrgEntityWrapper.eq(OmOrg.COLUMN_GUID, guidOrg);
        List<OmOrg> orgList = omOrgService.selectList(omOrgEntityWrapper);
        if (orgList.size() != 1) {
            throw new OrgManagementException(OMExceptionCodes.ORGANIZATION_NOT_EXIST_BY_GUID_ORG, wrap(guidOrg));
        }
        OmOrg org = orgList.get(0);
        OmGroup og = new OmGroup();
        //补充信息
        og.setGroupCode(genGroupCode(groupType.getValue()));
        og.setGroupStatus(OmGroupStatus.RUNNING);
        // 新增节点都先算叶子节点 Y
        og.setIsleaf(YON.YES);
        //开启时间
        og.setStartDate(new Date());
        // 新增时子节点数为0
        og.setSubCount(new BigDecimal(0));
        //TODO
        og.setUpdator("");
        //收集入参
        og.setGroupName(groupName);
        og.setDisplayOrder(new BigDecimal(selectCount(new EntityWrapper<OmGroup>().isNull(OmGroup.COLUMN_GUID_PARENTS))));
        og.setGuidOrg(guidOrg);
        og.setGroupType(groupType);
        og.setGroupDesc(groupDesc);
        if(StringUtil.isEmpty(parentGroupCode)){
            // 补充工作组层次，根节点层次为 0
            og.setGroupLevel(new BigDecimal(0));
            // 补充父机构，根节点没有父机构
            og.setGuidParents(null);
            // 设置工作组序列,根工作组直接用guid
            og.setGroupSeq(og.getGuid());
            this.baseMapper.insert(og);

            omGroup.setGroupSeq(og.getGuid());
        }else{
            //新建子工作组
            //先获取父工作组信息
            EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
            omGroupEntityWrapper.eq(OmGroup.COLUMN_GUID, parentGroupCode);
            List<OmGroup> ogList = this.baseMapper.selectList(omGroupEntityWrapper);
            if (ogList.size() != 1) {
                throw new OrgManagementException(OMExceptionCodes.GROUP_NOT_EXIST_BY_GROUP_CODE, wrap(parentGroupCode));
            }
            OmGroup parentOg = ogList.get(0);
            //更新父工作组信息
            parentOg.setIsleaf(YON.NO);
            int count = parentOg.getSubCount().intValue() + 1;
            parentOg.setSubCount(new BigDecimal(count));
            parentOg.setLastupdate(new Date());
            // 补充工作组层次
            int level = parentOg.getGroupLevel().intValue() + 1;
            og.setGroupLevel(new BigDecimal(level));
            // 补充父机构，根节点没有父机构
            og.setGuidParents(parentOg.getGuid());
            og.setDisplayOrder(new BigDecimal(selectCount(new EntityWrapper<OmGroup>().eq(OmGroup
                    .COLUMN_GUID_PARENTS,parentOg.getGuid()))));
            // 设置工作组序列,根工作组直接用guid
            og.setGroupSeq(parentOg.getGroupSeq() + "." + og.getGuid());
            this.baseMapper.insert(og);

            this.baseMapper.update(parentOg,omGroupEntityWrapper);

            //设置工作组序列
            omGroup.setGroupSeq(parentOg.getGroupSeq() + "." + og.getGuid());


        }
        EntityWrapper<OmGroup> omGroupEntity = new EntityWrapper<>();
        omGroupEntity.eq(OmGroup.COLUMN_GROUP_CODE, og.getGroupCode());

        List<OmGroup> omGroupList = this.baseMapper.selectList(omGroupEntity);
        if (omGroupList.size() != 1) {
            throw new OrgManagementException(OMExceptionCodes.GROUP_NOT_EXIST_BY_GROUP_CODE, wrap(og.getGroupCode()));
        }

        this.baseMapper.update(omGroup,omGroupEntity);
    }

    @Override
    public Page<OmGroup> queryAllGroup(Page<OmGroup> page) throws OrgManagementException {
        return selectPage(page,null);
    }

    @Override
    public OmGroup copyGroup(String fromGroupCode, String toOrgCode, String toParentGroupCode) throws OrgManagementException {
        return null;
    }

    @Override
    public OmGroup copyGroupDeep(String fromGroupCode, String toOrgCode, String toParentGroupCode, boolean copyChild, boolean copyApp, boolean copyPosition, boolean copyEmployee) throws OrgManagementException {
        return null;
    }

    @Override
    public OmGroup moveGroup(String targetGuid, String moveGuid, BigDecimal order) throws OrgManagementException {
        // 查询移动的工作组信息及其下属的所有工作组信息
        OmGroup omGroup = selectById(moveGuid);
        if (omGroup == null) {
            throw new OrgManagementException(ExceptionCodes.FAILURE_WHEN_QUERY);
        }

        List<OmGroup> childGroupList = selectList(new EntityWrapper<OmGroup>().like(OmGroup.COLUMN_GROUP_SEQ,
                moveGuid));
        // 目标工作组节点
        OmGroup goalGroup = new OmGroup();
        if (!"null".equals(targetGuid)){
            goalGroup= selectById(targetGuid);
            if (goalGroup == null) {
                throw new OrgManagementException(ExceptionCodes.NOT_FOUND_WHEN_QUERY);
            }
        }

        // 源工作组节点
        // 源工作组GUID
        String sourceGuid = omGroup.getGuidParents();
        // 源工作组显示顺序
        BigDecimal sourceOrder = omGroup.getDisplayOrder();
        String sourceSeq = omGroup.getGroupSeq();

        // 重新排序源工作组下的子工作组自减
        if (StringUtil.isNotEmpty(sourceGuid)){
            this.baseMapper.reorderOrg(sourceGuid, sourceOrder, REORDER_AUTO_MINUS);
        }else {
            this.baseMapper.reorderOrgNoParentId(sourceOrder,REORDER_AUTO_MINUS);
        }
        // 处理移动工作组信息
        if ("null".equals(targetGuid)){
            // 改变序列
            omGroup.setGroupSeq(omGroup.getGuid());
            // 改变父工作组信息
            omGroup.setGuidParents(null);
            // 改变显示顺序
            omGroup.setDisplayOrder(order);
            omGroup.setSubCount(new BigDecimal(0));
            this.baseMapper.reorderOrgNoParentId(order, REORDER_AUTO_PLUS);
        }else {
            // 改变父工作组信息
            omGroup.setGuidParents(targetGuid);
            // 改变序列
            omGroup.setGroupSeq(goalGroup.getGroupSeq()+ "." + moveGuid);
            // 改变显示顺序
            omGroup.setDisplayOrder(order);
            omGroup.setSubCount(new BigDecimal(goalGroup.getSubCount().intValue() + 1));
            // 重新排序目标工作组下的子工作组自增
            this.baseMapper.reorderOrg(targetGuid, order, REORDER_AUTO_PLUS);
        }

        // 更改移动的重组工作组信息
        updateAllColumnById(omGroup);
        // 如果改变了父节点需要同步改变子节点
        if (!"null".equals(targetGuid)) {
            if (!targetGuid.equals(omGroup.getGuidParents())) {
                // 更改移动工作组下的子菜单
                for (OmGroup omGroupQue : childGroupList) {
                    // 排除当前移动工作组
                    if (!StringUtil.equals(omGroupQue.getGuid(), moveGuid)) {
                        // 更新工作组序列
                        // update 表名 set 字段名=REPLACE (字段名,'原来的值','要修改的值')
                        String seq = omGroupQue.getGroupSeq();
                        OmGroup omGroupUpdate = new OmGroup();
                        omGroupUpdate.setGuid(omGroupQue.getGuid());
                        omGroupUpdate.setGroupSeq(seq.replace(sourceSeq, omGroup.getGroupSeq()));
                        updateById(omGroupUpdate);
                    }
                }
            }
        }

         return omGroup;
    }

    @Override
    public boolean updateGroup(OmGroup newOmGroup) throws OrgManagementException {

        boolean exist = false;

        Wrapper<OmGroup> wrapper = new EntityWrapper<>();
        wrapper.eq(OmGroup.COLUMN_GROUP_CODE,newOmGroup.getGroupCode());
        List<OmGroup> lists = selectList(wrapper);

        for (OmGroup omGroup:lists){
            if (!(omGroup.getGuid().equals(newOmGroup.getGuid()))){
                return exist;
            }
        }

        exist = true;

        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.eq(OmGroup.COLUMN_GROUP_CODE,newOmGroup.getGroupCode());
        this.baseMapper.update(newOmGroup,omGroupEntityWrapper);

        return exist;
    }

    @Override
    public void deleteGroup(String groupCode) throws OrgManagementException {
        //校验状态
        OmGroup og = queryGroupByCode(groupCode);
        if (OmGroupStatus.RUNNING.equals(og.getGroupStatus())) {
            throw new OrgManagementException(OMExceptionCodes.FAILURE_DELETE_RERUNNING_GROUP);
        }
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.like(OmGroup.COLUMN_GROUP_SEQ, og.getGroupSeq());

        //删除并修改工作组结束时间
        OmGroup omGroup = new OmGroup();
        omGroup.setGroupCode(groupCode);
        omGroup.setEndDate(new Date());
        updateGroup(omGroup);
        this.baseMapper.delete(omGroupEntityWrapper);

        //删除完工作组之后判断其父工作组下是否还有子工作组,如果没有子工作组则将是否叶子节点改为是
        if (StringUtil.isNotEmpty(og.getGuidParents())){
            OmGroup omGroupParent = selectById(og.getGuidParents());
            if (null != omGroupParent){
               Wrapper<OmGroup> wrapper = new EntityWrapper<>();
               wrapper.eq(OmGroup.COLUMN_GUID_PARENTS,omGroupParent.getGuid());
               List<OmGroup> omGroups = selectList(wrapper);
               if (0 == omGroups.size()){
                   omGroupParent.setIsleaf(YON.YES);
                   updateById(omGroupParent);
               }
            }
        }
    }

    @Override
    public void cancelGroup(String groupCode) throws OrgManagementException {
        OmGroup og = queryGroupByCode(groupCode);
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.like(OmGroup.COLUMN_GROUP_SEQ, og.getGroupSeq());
        omGroupEntityWrapper.notIn(OmGroup.COLUMN_GROUP_CODE,groupCode);
        List<OmGroup> ogList = this.baseMapper.selectList(omGroupEntityWrapper);

        if(ogList.size() > 0){
            for (OmGroup omGroup : ogList) {
                if (omGroup.getGroupStatus().equals(OmGroupStatus.RUNNING)) {
                    throw new OrgManagementException(OMExceptionCodes.GROUP_CHILDS_IS_RUNNING,wrap(groupCode));
                }
            }
        }
        og.setGroupStatus(OmGroupStatus.ANCEL);

        updateGroup(og);
    }

    @Override
    public void reenableGroup(String groupCode, String reenableChild) throws OrgManagementException {
        //调用方法中已经有参数检验
        OmGroup og = queryGroupByCode(groupCode);
        if(og.getGroupStatus().equals(OmGroupStatus.RUNNING)){
            throw new OrgManagementException(OMExceptionCodes.GROUP_CHILDS_IS_RUNNING,wrap(og.getGroupName()));
        }else{
            og.setGroupStatus(OmGroupStatus.RUNNING);
            this.baseMapper.updateById(og);
            if(reenableChild.equals("true") || reenableChild.equals("TRUE")){
                EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
                omGroupEntityWrapper.like(OmGroup.COLUMN_GROUP_SEQ,og.getGuid());
                OmGroup omGroup = new OmGroup();
                omGroup.setGroupStatus(OmGroupStatus.RUNNING);
                this.baseMapper.update(omGroup,omGroupEntityWrapper);
            }
        }

    }

    @Override
    public OmGroup queryGroupByCode(String groupCode) {
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.eq(OmGroup.COLUMN_GROUP_CODE, groupCode);
        List<OmGroup> ogList = this.baseMapper.selectList(omGroupEntityWrapper);
        if (ogList.size() != 1) {
            throw new OrgManagementException(OMExceptionCodes.GROUP_NOT_EXIST_BY_GROUP_CODE, wrap(groupCode));
        }
        OmGroup og = ogList.get(0);
        return og;
    }

    @Override
    public Page<OmGroup> selectRootGroup(Page<OmGroup> page) {
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.isNull(OmGroup.COLUMN_GUID_PARENTS);
        return selectPage(page, omGroupEntityWrapper);
    }

    @Override
    public Page<OmGroup> selectChildGroup(String groupCode, Page<OmGroup> page) {
        OmGroup og = queryGroupByCode(groupCode);
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.eq(OmGroup.COLUMN_GUID_PARENTS, og.getGuid());
        return selectPage(page, omGroupEntityWrapper);
    }

    @Override
    public List<OmPositionDetail> selectPosition(String groupCode) {
        return null;
    }

    @Override
    public Page<OmEmployeeOperatorDetail> selectEmployee(String groupCode, Page<OmEmployee> page) {
        OmGroup og = queryGroupByCode(groupCode);
        EntityWrapper<OmEmpGroup> omEmpGroupEntityWrapper = new EntityWrapper<>();
        omEmpGroupEntityWrapper.eq(OmEmpGroup.COLUMN_GUID_GROUP, og.getGuid());
        List<OmEmpGroup> oegList = omEmpGroupService.selectList(omEmpGroupEntityWrapper);
        Page<OmEmployeeOperatorDetail> empList = new Page<OmEmployeeOperatorDetail>();
        if (oegList.size() == 0) {
            return empList;
        } else {
            List<String> guidList = new ArrayList<>();
            for (OmEmpGroup oeg : oegList) {
                guidList.add(oeg.getGuidEmp());
            }
            EntityWrapper<OmEmployee> omEmployeeEntityWrapper = new EntityWrapper<>();
            omEmployeeEntityWrapper.in(OmEmployee.COLUMN_GUID, guidList);

            Page<OmEmployeeOperatorDetail> employeeOperatorDetailPage = new Page<OmEmployeeOperatorDetail>();
            List<OmEmployeeOperatorDetail> employeeOperatorDetailList= new ArrayList<OmEmployeeOperatorDetail>();

            Page<OmEmployee> employeePage = omEmployeeService.selectPage(page,omEmployeeEntityWrapper);
            List<OmEmployee> employeeList = employeePage.getRecords();

            //获取操作员姓名并放到新的employeeOperatorDetailList中
            employeeOperatorDetailList = setOperatorName(employeeList,og.getGuid());

            employeeOperatorDetailPage.setCondition(employeePage.getCondition());
            employeeOperatorDetailPage.setRecords(employeeOperatorDetailList);
            employeeOperatorDetailPage.setTotal(employeePage.getTotal());
            employeeOperatorDetailPage.setSize(employeePage.getSize());
            employeeOperatorDetailPage.setCurrent(employeePage.getCurrent());


            return employeeOperatorDetailPage;
        }
    }

    /**
     * 查询在该工作组的员工列表(过滤查询)
     */
    @Override
    public Page<OmEmployeeOperatorDetail> selectEmployeeFilter(String groupCode, Page<OmEmployee> page, Wrapper<OmEmployee> wrapper) {
        //判断group是否存在,获取到存在的group
        OmGroup og = queryGroupByCode(groupCode);

        Page<OmEmployee> employeePage = new Page<OmEmployee>();

        if (null == wrapper){
            //没有任何参数
            employeePage = page.setRecords(this.baseMapper.selectEmployee(page,og.getGuid()));
        }else {
            //有参数
            OmEmployee omEmployee = wrapper.getEntity();
            String empCode = null;
            String empName = null;
            String guidPosition = null;
            String guidEmpMajor = null;

            if (!StringUtil.isEmpty(omEmployee.getEmpCode())){
                empCode = "%"+omEmployee.getEmpCode()+"%";
            }
            if (!StringUtil.isEmpty(omEmployee.getEmpName())){
                empName = "%"+omEmployee.getEmpName()+"%";
            }
            if (!StringUtil.isEmpty(omEmployee.getGuidPosition())){
                guidPosition = omEmployee.getGuidPosition();
            }
            if (!StringUtil.isEmpty(omEmployee.getGuidEmpMajor())){
                guidEmpMajor = omEmployee.getGuidEmpMajor();
            }

            employeePage = page.setRecords(this.baseMapper.selectEmployeeFilter(page,og.getGuid(),empCode,empName,omEmployee
                            .getGender(),
                    guidPosition,guidEmpMajor,omEmployee.getEmpstatus()));
        }


        List<OmEmployee> employeeList = employeePage.getRecords();

        Page<OmEmployeeOperatorDetail> employeeOperatorDetailPage = new Page<OmEmployeeOperatorDetail>();
        List<OmEmployeeOperatorDetail> employeeOperatorDetailList= new ArrayList<OmEmployeeOperatorDetail>();

        //获取操作员姓名并放到新的employeeOperatorDetailList中
        employeeOperatorDetailList = setOperatorName(employeeList,og.getGuid());

        employeeOperatorDetailPage.setCondition(employeePage.getCondition());
        employeeOperatorDetailPage.setRecords(employeeOperatorDetailList);
        employeeOperatorDetailPage.setTotal(employeePage.getTotal());
        employeeOperatorDetailPage.setSize(employeePage.getSize());
        employeeOperatorDetailPage.setCurrent(employeePage.getCurrent());


        return employeeOperatorDetailPage;
    }

    //获取操作员姓名并放到新的List中,将岗位名称放入List中
    private List<OmEmployeeOperatorDetail> setOperatorName(List<OmEmployee> employeeList,String groupGuid){

        List<OmEmployeeOperatorDetail> employeeOperatorDetailList = new ArrayList<OmEmployeeOperatorDetail>();

        for (OmEmployee omEmployee : employeeList){
            if (null != omEmployee){

                String operatorName = "";
                String positionName = "";

                if (StringUtil.isNotEmpty(omEmployee.getGuidOperator())){
                    AcOperator acOperator = operatorService.selectById(omEmployee.getGuidOperator());
                    if (null != acOperator){
                        operatorName = acOperator.getOperatorName();
                    }
                }

                //获取工作组下岗位信息
                Wrapper<OmPosition> wrapper = new EntityWrapper<OmPosition>();
                wrapper.eq(OmPosition.COLUMN_GUID_MAPPING,groupGuid);
                List<OmPosition> positionGuidList = omPositionService.selectList(wrapper);
                if (0 != positionGuidList.size()){
                    for (OmPosition omPosition : positionGuidList){
                        if (null != omPosition){
                            Wrapper<OmEmpPosition> empPositionWrapper = new EntityWrapper<OmEmpPosition>();
                            empPositionWrapper.eq(OmEmpPosition.COLUMN_GUID_EMP,omEmployee.getGuid());
                            empPositionWrapper.eq(OmEmpPosition.COLUMN_GUID_POSITION,omPosition.getGuid());

                            OmEmpPosition omEmpPosition = omEmpPositionService.selectOne(empPositionWrapper);
                            if (null != omEmpPosition){
                                    positionName = omPosition.getPositionName();
                                    break;
                            }
                        }
                    }
                }

                OmEmployeeOperatorDetail omEmployeeOperatorDetail = new OmEmployeeOperatorDetail(omEmployee, operatorName,positionName);
                employeeOperatorDetailList.add(omEmployeeOperatorDetail);
            }
        }
        return employeeOperatorDetailList;
    }

    @Override
    public List<OmEmployee> selectEmpNotInGroup(String guidOrg, String groupCode) {
        return this.baseMapper.selectOrgEmpNotInGroup(guidOrg,groupCode);
    }

    @Override
    public Page<OmGroupPositionDetail> selectPositionInGroup(String groupCode, Page<OmPosition> page, Wrapper<OmPosition> wrapper) {
        //查询方法中自带参数校验
        OmGroup og = queryGroupByCode(groupCode);

//        EntityWrapper<OmGroupPosition> omGroupPositionEntityWrapper = new EntityWrapper<>();
//        omGroupPositionEntityWrapper.eq(OmGroupPosition.COLUMN_GUID_GROUP, og.getGuid());
//        Page<OmPosition> opPage = new Page<>();
//        List<OmGroupPosition> ogpList = omGroupPositionService.selectList(omGroupPositionEntityWrapper);
//        if (ogpList.isEmpty()) {
//            Page<OmGroupPositionDetail> gropOpPage = new Page<OmGroupPositionDetail>();
//            return gropOpPage;
//        }
//        List<String> posGuidList = new ArrayList<>();
//        for (OmGroupPosition ogp : ogpList) {
//            posGuidList.add(ogp.getGuidPosition());
//        }
        if (null == wrapper.getEntity()){
            wrapper = new EntityWrapper<OmPosition>();
            wrapper.eq(OmPosition.COLUMN_GUID_MAPPING,og.getGuid());
            wrapper.orderBy(OmPosition.COLUMN_POSITION_LEVEL,true);
            wrapper.orderBy(OmPosition.COLUMN_POSITION_SEQ,true);
        }else {
            wrapper.in(OmPosition.COLUMN_GUID_MAPPING,og.getGuid());
            wrapper.orderBy(OmPosition.COLUMN_POSITION_LEVEL,true);
            wrapper.orderBy(OmPosition.COLUMN_POSITION_SEQ,true);
        }

        Page<OmPosition> positionPage = omPositionService.selectPage(page, wrapper);
        List<OmPosition> positionList = positionPage.getRecords();
        if (0 == positionList.size()){
            return new Page<OmGroupPositionDetail>();
        }

        List<OmGroupPositionDetail> groupPositionList = new ArrayList<OmGroupPositionDetail>();
        for (OmPosition omPosition :positionList){
            if (null != omPosition){
                String parentName = "";
                if (StringUtil.isNotEmpty(omPosition.getGuidParents())){
                    parentName = this.baseMapper.selectPositionName(omPosition.getGuidParents());
                }
                int empNum = this.baseMapper.selectEmpNumByPosition(omPosition.getGuid());
                OmGroupPositionDetail omGroupPositionDetail = new OmGroupPositionDetail(omPosition,empNum,parentName);
                groupPositionList.add(omGroupPositionDetail);
            }
        }

        Page<OmGroupPositionDetail> groupPositionDetailPage = new Page<OmGroupPositionDetail>();

        groupPositionDetailPage.setRecords(groupPositionList);
        groupPositionDetailPage.setCurrent(positionPage.getCurrent());
        groupPositionDetailPage.setSize(positionPage.getSize());
        groupPositionDetailPage.setTotal(positionPage.getTotal());


        return groupPositionDetailPage;
    }

    @Override
    public List<OmPosition> selectPositionInGroupNotPage(String groupCode) {
        //查询方法中自带参数校验
        OmGroup og = queryGroupByCode(groupCode);
//        EntityWrapper<OmGroupPosition> omGroupPositionEntityWrapper = new EntityWrapper<>();
//        omGroupPositionEntityWrapper.eq(OmGroupPosition.COLUMN_GUID_GROUP, og.getGuid());
//        List<OmPosition> opList = new ArrayList<>();
//        List<OmGroupPosition> ogpList = omGroupPositionService.selectList(omGroupPositionEntityWrapper);
//        if (ogpList.isEmpty()) {
//            return opList;
//        }
//        List<String> posGuidList = new ArrayList<>();
//        for (OmGroupPosition ogp : ogpList) {
//            posGuidList.add(ogp.getGuidPosition());
//        }
        EntityWrapper<OmPosition> omPositionEntityWrapper = new EntityWrapper<>();
        omPositionEntityWrapper.in(OmPosition.COLUMN_GUID_MAPPING, og.getGuid());
        return omPositionService.selectList(omPositionEntityWrapper);
    }

//    @Override
//    public Page<OmPosition> selectPositionNotInGroup(String groupCode, Page<OmPosition> page) {
//        OmGroup og = queryGroupByCode(groupCode);
//
//        //查询方法中自带参数校验
//        EntityWrapper<OmGroupPosition> omGroupPositionEntityWrapper = new EntityWrapper<>();
//        omGroupPositionEntityWrapper.eq(OmGroupPosition.COLUMN_GUID_GROUP, og.getGuid());
//        List<OmGroupPosition> ogpList = omGroupPositionService.selectList(omGroupPositionEntityWrapper);
//        if (ogpList.isEmpty()) {
//            return new Page<>();
//        }
//        List<String> posGuidList = new ArrayList<>();
//        for (OmGroupPosition ogp : ogpList) {
//            posGuidList.add(ogp.getGuidPosition());
//        }
//
//        EntityWrapper<OmPosition> omPositionEntityWrapper = new EntityWrapper<>();
//        omPositionEntityWrapper.eq(OmPosition.COLUMN_GUID_ORG, og.getGuidOrg());
//        omPositionEntityWrapper.eq(OmPosition.COLUMN_POSITION_TYPE, "01");
//        omPositionEntityWrapper.notIn(OmPosition.COLUMN_GUID, posGuidList);
//
//        return omPositionService.selectPage(page, omPositionEntityWrapper);
//    }

    @Override
    public List<AcRole> selectRole(String groupCode) {
        return null;
    }

    @Override
    public Page<OmGroup> selectAllchild(String groupCode, Page<OmGroup> page) {
        OmGroup parentog = queryGroupByCode(groupCode);
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.eq(OmGroup.COLUMN_GUID_PARENTS, parentog.getGuid());
        return selectPage(page,omGroupEntityWrapper);
    }

    @Override
    public void insertGroupPosition(String groupCode, OmPositionRequest omPositionRequest) {

        OmGroup og = queryGroupByCode(groupCode);
        omPositionRequest.setGuidMapping(og.getGuid());
        omPositionRequest.setPositionType(OmPositionType.WORKINGGROUP);
        if(StringUtil.isEmpty(omPositionRequest.getGuidParents())){
            //添加根岗位
            omPositionService.addRoot(omPositionRequest);
        }else{
            //添加子岗位
            omPositionService.addChild(omPositionRequest);
        }
    }

//    @Override
//    public void deleteGroupPosition(String groupCode, String positionGuid) {
//        OmGroup omGroup = queryGroupByCode(groupCode);
//        EntityWrapper<OmGroupPosition> omGroupPositionEntityWrapper = new EntityWrapper<>();
//        omGroupPositionEntityWrapper.eq(OmGroupPosition.COLUMN_GUID_POSITION,positionGuid);
//        omGroupPositionEntityWrapper.eq(OmGroupPosition.COLUMN_GUID_GROUP,omGroup.getGuid());
//        omGroupPositionService.delete(omGroupPositionEntityWrapper);
//    }

    @Override
    public String selectPositionGuidByCode(String positionCode) {
        EntityWrapper<OmPosition> omPositionEntityWrapper = new EntityWrapper<>();
        omPositionEntityWrapper.eq(OmPosition.COLUMN_POSITION_CODE,positionCode);
        List<OmPosition> opList = omPositionService.selectList(omPositionEntityWrapper);
        if (opList.size() != 1) {
            throw new OrgManagementException(OMExceptionCodes.POSITANIZATION_NOT_EXIST_BY_POSIT_CODE, wrap(positionCode));
        }
        OmPosition parentOg = opList.get(0);

        return parentOg.getGuid();
    }

    @Override
    public Page<OmGroup> selectByGroupName(String groupName,Page<OmGroup> page) {
        EntityWrapper<OmGroup> omGroupEntityWrapper = new EntityWrapper<>();
        omGroupEntityWrapper.eq(OmGroup.COLUMN_GROUP_NAME, groupName);
        Page<OmGroup> list =  selectPage(page, omGroupEntityWrapper);
        return list;
    }

    @Override
    public Page<AcApp> selectApp(String groupCode, Page<AcApp> page) {
        OmGroup og = queryGroupByCode(groupCode);
        EntityWrapper<OmGroupApp> OmGroupAppEntityWrapper = new EntityWrapper<>();
        OmGroupAppEntityWrapper.eq(OmGroupApp.COLUMN_GUID_GROUP, og.getGuid());
        List<OmGroupApp> ogpList = omGroupAppService.selectList(OmGroupAppEntityWrapper);
        if (ogpList.size() == 0) {
            return new Page<AcApp>();
        }
        List<String> guidList = new ArrayList<>();
        for (OmGroupApp ogp : ogpList) {
            guidList.add(ogp.getGuidApp());
        }
        EntityWrapper<AcApp> AcAppEntityWrapper = new EntityWrapper<>();
        AcAppEntityWrapper.in(AcApp.COLUMN_GUID, guidList);
        Page<AcApp> acApp = acAppService.selectPage(page,AcAppEntityWrapper);
        return acApp;
    }

    @Override
    public List<AcApp> selectAppNotInGroup(String groupCode) {

         return this.baseMapper.selectAppNotInGroup(groupCode);
    }

    @Override
    public void addGroupApp(List<String> appGuidList, String groupCode) {
        List<OmGroupApp> ogpList = new ArrayList<>();
        OmGroup og = queryGroupByCode(groupCode);
        if (og == null) {
            throw new OrgManagementException(OMExceptionCodes.GROUP_NOT_EXIST_BY_GROUP_CODE, wrap(groupCode));
        }
        EntityWrapper<OmGroupApp> omEmpGroupEntityWrapper = new EntityWrapper<>();
        omEmpGroupEntityWrapper.eq(OmGroupApp.COLUMN_GUID_GROUP, og.getGuid());
        omEmpGroupEntityWrapper.in(OmGroupApp.COLUMN_GUID_APP, appGuidList);
        List<OmGroupApp> oegList = omGroupAppService.selectList(omEmpGroupEntityWrapper);
        if (oegList.size() > 0) {
            throw new OrgManagementException(OMExceptionCodes.IS_EXIST_BY_GROUP_CREAT_APP, wrap(groupCode));
        }

        for (String guidApp : appGuidList){
            OmGroupApp ogp = new OmGroupApp();
            ogp.setGuidApp(guidApp);
            ogp.setGuidGroup(og.getGuid());
            ogpList.add(ogp);
        }
        omGroupAppService.insertBatch(ogpList);
    }

    @Override
    public void deleteGroupApp(String groupCode,String guidApp) {
        OmGroup omGroup = queryGroupByCode(groupCode);
        EntityWrapper<OmGroupApp> omGroupAppEntityWrapper = new EntityWrapper<>();
        omGroupAppEntityWrapper.eq(OmGroupApp.COLUMN_GUID_APP, guidApp);
        omGroupAppEntityWrapper.eq(OmGroupApp.COLUMN_GUID_GROUP, omGroup.getGuid());
        omGroupAppService.delete(omGroupAppEntityWrapper);
    }

    @Override
    public List<TreeDetail> selectGroupTree() {

//        TreeDetail treeDetail = new TreeDetail();
//
//        //创建子机构的list
//        List<Tree> list = new ArrayList<Tree>();
//
//
//        if("null".equals(guid)){
//            Wrapper<OmGroup> wrapper = new EntityWrapper<OmGroup>();
//            wrapper.isNull(OmGroup.COLUMN_GUID_PARENTS);
//            wrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER);
//            List<OmGroup> queryList = selectList(wrapper);
//
//            list = setGroupToList(queryList);
//        }else {
//            OmGroup omGroup = selectById(guid);
//
//            //查询子机构字典
//            Wrapper<OmGroup> wrapper = new EntityWrapper<OmGroup>();
//            wrapper.eq(OmGroup.COLUMN_GUID_PARENTS,guid);
//            wrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER);
//
//            List<OmGroup> queryList = selectList(wrapper);
//
//            list = setGroupToList(queryList);
//
//            //收集查询出来的结果
//            treeDetail.setGuid(omGroup.getGuid());
//            treeDetail.setCode(omGroup.getGroupCode());
//            treeDetail.setLabel(omGroup.getGroupName());
//            treeDetail.setIsleaf(omGroup.getIsleaf());
//        }
//        treeDetail.setChildren(list);
//
//        return treeDetail;

        List<TreeDetail> treeDetails = new LinkedList<>();

        //查询出所有的工作组
        Wrapper<OmGroup> groupWrapper = new EntityWrapper<>();
        groupWrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER,true);
        List<OmGroup> allGroups = selectList(groupWrapper);

        //将数据拼接为TreeDetail结构
        List<TreeDetail> allTrees = setGroupToTreeDetails(allGroups);
        //将数据拼接为树形结构
        treeDetails = setInAcMenuDetail(allTrees);

        return treeDetails;
    }

    /**
     * 根据姓名过滤查询工作组树结构
     */
    @Override
    public List<TreeDetail> selectGroupTreeFilter(String name) {

        List<TreeDetail> treeDetails = new LinkedList<>();

        //创建子机构的list
//        List<Tree> list = new ArrayList<Tree>();

//        if("null".equals(filterRequest.getGuid())){
//            Wrapper<OmGroup> wrapper = new EntityWrapper<OmGroup>();
//            wrapper.isNull(OmGroup.COLUMN_GUID_PARENTS);
//            wrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER);
//            wrapper.like(OmGroup.COLUMN_GROUP_NAME,filterRequest.getName());
//
//            List<OmGroup> queryList = selectList(wrapper);
//
//            list = setGroupToList(queryList);
//
//        }else {
//            OmGroup omGroup = selectById(filterRequest.getGuid());
//
//            //查询子机构字典
//            Wrapper<OmGroup> wrapper = new EntityWrapper<OmGroup>();
//            wrapper.eq(OmGroup.COLUMN_GUID_PARENTS,filterRequest.getGuid());
//            wrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER);
//            wrapper.like(OmGroup.COLUMN_GROUP_NAME,filterRequest.getName());
//
//            List<OmGroup> queryList = selectList(wrapper);
//
//            list = setGroupToList(queryList);
//
//            //收集查询出来的结果
//            treeDetail.setGuid(omGroup.getGuid());
//            treeDetail.setCode(omGroup.getGroupCode());
//            treeDetail.setLabel(omGroup.getGroupName());
//            treeDetail.setIsleaf(omGroup.getIsleaf());
//        }
//        treeDetail.setChildren(list);

        //查询出所有的工作组
        Wrapper<OmGroup> groupWrapper = new EntityWrapper<>();
        groupWrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER,true);
        List<OmGroup> allGroups = selectList(groupWrapper);

        if (StringUtil.isEmpty(name)){
            //将数据拼接为TreeDetail结构
            List<TreeDetail> allTrees = setGroupToTreeDetails(allGroups);
            //将数据拼接为树形结构
            treeDetails = setInAcMenuDetail(allTrees);
        }else {
            //查询工作组字典
            Wrapper<OmGroup> wrapper = new EntityWrapper<>();
            wrapper.orderBy(OmGroup.COLUMN_DISPLAY_ORDER,true);
            wrapper.like(OmGroup.COLUMN_GROUP_NAME,name);
            List<OmGroup> groups = selectList(wrapper);

            List<TreeDetail> details = new LinkedList<>();
            if (0 == groups.size()){
                return treeDetails;
            }else {
                //将数据拼接为TreeDetail结构
               details = setGroupToTreeDetails(groups);
            }

            //找出所有需要排序的节点信息
            List<TreeDetail> resultList = new LinkedList<>();
            //将数据拼接为TreeDetail结构
            List<TreeDetail> allTrees = setGroupToTreeDetails(allGroups);
            Map<String,TreeDetail> allMap = new LinkedHashMap<>();
            if (0 != allTrees.size()){
                //查询结果非空,则循环拼接
                for (TreeDetail treeDetail : allTrees){
                    if (null != treeDetail){
                        allMap.put(treeDetail.getGuid(),treeDetail);
                    }
                }
            }

            for (int i = 0; i < details.size(); i++) {
                if (null != details.get(i).getData()) {
                    TreeDetail treeDetailSon = details.get(i);
                    resultList.add(treeDetailSon);
                    TreeDetail treeDetailFather = treeDetailSon;
                    while (null != allMap.get(treeDetailSon.getData()).getData()) {
                        treeDetailFather = allMap.get(treeDetailSon.getData());
                        resultList.add(treeDetailFather);
                        treeDetailSon = treeDetailFather;
                    }
                    resultList.add(allMap.get(treeDetailFather.getData()));
                }
            }

            //将数据拼接为树形结构
            treeDetails = setInAcMenuDetail(resultList);
        }
        return treeDetails;
    }

    //向工作组数据拼接为树结构
    private List<Tree> setGroupToList(List<OmGroup> queryList){

        if (0 == queryList.size()){
            return null;
        }

        List<Tree> list = new ArrayList<Tree>();
        for (OmGroup omGroupQuery: queryList) {
            if (null != omGroupQuery){
                Tree treeSon = new Tree();
                treeSon.setGuid(omGroupQuery.getGuid());
                treeSon.setCode(omGroupQuery.getGroupCode());
                treeSon.setLabel(omGroupQuery.getGroupName());
                treeSon.setIsleaf(omGroupQuery.getIsleaf());
                list.add(treeSon);
            }
        }
        return list;
    }

    //将工作组数据拼接为(TreeDetail)结构
    private List<TreeDetail> setGroupToTreeDetails(List<OmGroup> queryList){

        List<TreeDetail> list = new LinkedList<>();
        if (0 == queryList.size()){
            return list;
        }

        for (OmGroup omGroupQuery: queryList) {
            if (null != omGroupQuery){
                TreeDetail treeDetail = new TreeDetail();
                treeDetail.setGuid(omGroupQuery.getGuid());
                treeDetail.setCode(omGroupQuery.getGroupCode());
                treeDetail.setLabel(omGroupQuery.getGroupName());
                treeDetail.setIsleaf(omGroupQuery.getIsleaf());
                treeDetail.setData(omGroupQuery.getGuidParents());
                list.add(treeDetail);
            }
        }
        return list;
    }


    private List<TreeDetail> setInAcMenuDetail(List<TreeDetail> resultList){


        List<TreeDetail> detailExits = new LinkedList<>();
        if (0 == resultList.size()){
            return detailExits;
        }

        Map<String,TreeDetail> map = new LinkedHashMap<String, TreeDetail>();
        for (TreeDetail treeDetail : resultList){
            if (null != treeDetail){
                map.put(treeDetail.getGuid(),treeDetail);
            }
        }

        for(String key:map.keySet())
        {
            if (null != map.get(map.get(key).getData())){
                map.get(map.get(key).getData()).getChildrens().add(map.get(key));
            }else {
                detailExits.add(map.get(key));
            }
        }

        return detailExits;
    }


    /**
     * 把当前工作组数量转为8位字符串，不足部分以0左补齐
     */
    private Object toSeqNO(long totalOrgCount) {

        String t = String.valueOf(totalOrgCount) ;
        return org.tis.tools.core.utils.StringUtil.leftPad(t, 8, '0');

    }

    /**
     * 查询工作组下可分配给岗位的员工
     */
    @Override
    public List<OmEmployee> getPositionOutEmployee( OmGroup omGroup, String positionGuid) throws OrgManagementException {

        //判断岗位是否存在,是否在工作组下
        OmPosition omPosition = omPositionService.selectById(positionGuid);
        if (null == omPosition){
            throw new OrgManagementException(OMExceptionCodes.FAILURE_WHEN_QUERY_OM_POSITION);
        }

        //查询工作组下的员工
        List<OmEmployee> groupEmpList = this.baseMapper.selectEmpByGroup(omGroup.getGuid());
        //查询岗位下员工
        List<OmEmployee> positionEmpList = this.baseMapper.selectEmpByPosition(positionGuid);
        if (0 == groupEmpList.size()){
            return null;
        }
        //得出工作组下非该岗位的员工
        groupEmpList.removeAll(positionEmpList);

        return groupEmpList;
    }

    /**
     * 查询工作组下可分配的岗位
     */
    @Override
    public List<OmPosition> queryPositionByGroupId(String groupId, String positionId) throws OrgManagementException {

        Wrapper<OmPosition> wrapper = new EntityWrapper<OmPosition>();
        wrapper.eq(OmPosition.COLUMN_GUID_MAPPING,groupId);

        List<OmPosition> list = omPositionService.selectList(wrapper);

        if (0 != list.size()){
            if (StringUtil.isNotEmpty(positionId)){
                OmPosition omPosition = omPositionService.selectById(positionId);
                if (null != omPosition){
                    list.remove(omPosition);
                }
            }
        }

        return list;
    }
}

